export interface PercentOptions {
  /**
   * 是否添加百分比符号 default = true
   */
  isAddPercentSign?: boolean
  /**
   * 结果保留几位小数 default = 2
   */
  fractionDigits?: number
}

export interface ConvertToTenThousand {
  /**
   * 结果保留几位小数 default = 2
   */
  fractionDigits?: number
  /**
   * 是否进行千位符转换 default = true
   */
  isToThousands?: boolean
}
export class NumberUtils {
  /**
   * 计算百分比
   * @param divisor 除数
   * @param dividend 被除数
   * @param {PercentOptions} param2
   * @returns {string}
   */
  static percent(
    divisor: number,
    dividend: number,
    { isAddPercentSign = true, fractionDigits = 2 }: PercentOptions = {}
  ): string {
    let result = 0
    if (dividend !== 0) {
      result = (divisor / dividend) * 100
    }
    const symbol = isAddPercentSign ? '%' : ''
    return `${NumberUtils.retainFractionDigits(result, fractionDigits)}${symbol}`
  }

  /**
   * 如果数字大于10000 单位转换为万
   * @param number
   * @param param1
   */
  static convertToTenThousand(
    numberInput: number,
    { fractionDigits = 2, isToThousands = true }: ConvertToTenThousand = {}
  ) {
    const number = Number(numberInput)
    if (isNaN(number)) {
      return numberInput
    }
    const dividend = 10000
    let result: string | number = number
    let symbol = ''
    if (number >= dividend) {
      result = NumberUtils.retainFractionDigits(number / dividend, fractionDigits)
      symbol = '万'
    }
    if (isToThousands) {
      result = NumberUtils.toThousands(result)
    }
    return `${result}${symbol}`
  }

  /**
   * 保留几位小数
   * @param numberInput 数字输入
   * @param fractionDigits 保留位数  default = 2
   * @returns {number} 转换后的数字
   */
  static retainFractionDigits(numberInput: number, fractionDigits: number = 2) {
    const number = Number(numberInput)
    if (isNaN(number)) {
      return numberInput
    }
    const dividend = 10 ** fractionDigits
    if (fractionDigits > 0) {
      return Math.floor(number * dividend) / dividend
    } else {
      return Math.floor(number)
    }
  }

  /**
   * 千位符转换 1000 => 1,000
   * @param numberInput 要转换的数字
   * @returns {string}
   */
  static toThousands(numberInput: string | number): string {
    const number = Number(numberInput)
    if (isNaN(number)) {
      return numberInput as string
    }
    const numStr = number.toString()
    const reg = numStr.includes('.') ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(?:\d{3})+$)/g
    return numStr.replace(reg, '$1,')
  }
}
